package cn.tang.tframe.common.utils;


import cn.tang.tframe.common.utils.lang.StringUtils;

import java.math.BigDecimal;

/**
 * 数字相关工具
 * 
 * @author tanghc
 */
public class MathUtils {

	/**
	 * BigDecimal 相加。考虑npe
	 *
	 */
	public static BigDecimal add(BigDecimal... nums) {
		BigDecimal sum = BigDecimal.ZERO;
		if (null != nums) {
			for (BigDecimal n : nums) {
				if (null != n) {
					sum = sum.add(n);
				}
			}
		}
		return sum;
	}

	public static Number add(Number... nums) {
		Long sum = 0L;
		if (null != nums) {
			for (Number n : nums) {
				if (null != n) {
					sum += n.longValue();
				}
			}
		}
		return sum;
	}

	public static BigDecimal trimToZero(BigDecimal amount) {
		if (null == amount) {
			return BigDecimal.ZERO;
		}
		return amount;
	}


	public static BigDecimal trimToZero(Number number) {
		if (null == number) {
			return BigDecimal.ZERO;
		}
		return new BigDecimal(number.toString());
	}

	public static BigDecimal percentToBigDecimal(String percentString) {
		try {
			if (StringUtils.isBlank(percentString) || !percentString.endsWith("%")) {
				return BigDecimal.ZERO;
			}
			return new BigDecimal(percentString.substring(0, percentString.lastIndexOf("%")));
		} catch (Exception e) {
		}
		return BigDecimal.ZERO;
	}

	/**
	 * BigDecimal null转成0
	 */
	public static BigDecimal convertNullToZero(BigDecimal v) {
		return null == v ? BigDecimal.ZERO : v;
	}
	public static int fastAbs(final int value) {
		return value & Integer.MAX_VALUE;
	}

	public static long roundToNearestMultipleOf(final long num, final long multipleOf) {
		if (num < 0) {
			throw new IllegalArgumentException("num cannot be negative");
		}
		if (multipleOf < 1) {
			throw new IllegalArgumentException("cannot round to nearest multiple of values less than 1");
		}
		if (num < multipleOf) {
			return multipleOf;
		}
		if ((num % multipleOf) >= (multipleOf / 2.0)) {
			return (num + multipleOf) - (num % multipleOf);
		} else {
			return num - (num % multipleOf);
		}
	}
	// public static Integer toInt(Number number){
	// if(number == null){
	// return null;
	// }
	// return number.intValue();
	// }
	public static void main(String[] args) {
		System.out.println(percentToBigDecimal("12.3%"));
	}
}
